package build_dao

import (
	"fmt"
	"go_server/game_server/database/mysql"
	"go_server/zinx/zlog"
	"go_server/zinx/zutils"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type Map struct {
	Id string `gorm:"column:Id;primary"`
	RoleId int64 `gorm:"column:role_id"`
	MapId int32 `gorm:"column:map_id"`
	ZId int32 `gorm:"column:z_id"`
	XInfo []byte `gorm:"column:x_info"`
}


func (Map) TableName() string {
	return "map_info"
}

var(
	all_map_field = zutils.GetGormFields(Map{})
)

func GetMapByKey(key string) *Map {
	db := mysql.GetServerDBConnection()
	var userMap Map
	if err := db.Select(all_map_field).Where("Id=?", key).First(&userMap).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetMapByKey ERR!!! Id: %s, err: %v", key, err)
		}
		return nil
	}
	return &userMap
}

func GetMapByMapId(roleId int64, mapId int32) []*Map {
	db := mysql.GetServerDBConnection()
	var xInfos []*Map
	if err := db.Select(all_map_field).Where(&Map{RoleId: roleId, MapId: mapId}).Find(&xInfos).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetMapByMapId ERR!!! roleId: %d, mapId: %d err: %v", roleId, mapId, err)
		}
		return nil
	}
	return xInfos
}

func CreateOrUpdateMapData(mapId int32, datamap [][]byte, roleId int64) {
	mapArr := make([]*Map, 0)
	for zId, xRow := range datamap {
		userMap := &Map{
			RoleId:    roleId,
			MapId:     mapId,
			ZId: int32(zId),
			XInfo: xRow,
			Id:        fmt.Sprint(roleId) + "-" + fmt.Sprint(mapId) + "-" + fmt.Sprint(zId),
		}
		mapArr = append(mapArr, userMap)
	}

	db := mysql.GetServerDBConnection()
	if err := db.Clauses(clause.OnConflict{
		Columns: []clause.Column{{Name: "Id"}},
		DoUpdates: clause.AssignmentColumns([]string{"x_info"}),
	}).Create(mapArr).Error;err != nil {
		zlog.Errorf("create or update Map %v data failed: %v", mapArr, err)
	}
}
